import { useCallback, useEffect, useState } from 'react';
import { playFullNotification, playNotificationSound, playVoiceNotification, preloadAudio } from '@/lib/audio';
import { useAudio } from '@/contexts/AudioContext';

export type NotificationType = 'message' | 'alert' | 'success' | 'error';

/**
 * 音频通知钩子
 * 用于在消息通知时播放声音和语音提示
 */
export function useAudioNotification() {
  const { settings, isAudioReady } = useAudio();
  const [isPreloaded, setIsPreloaded] = useState(false);

  // 组件挂载时预加载音频
  useEffect(() => {
    const preloadAudioFiles = async () => {
      try {
        await preloadAudio();
        setIsPreloaded(true);
      } catch (error) {
        console.warn('音频预加载失败:', error);
        setIsPreloaded(true); // 即使失败也标记为已预加载，使用备用方案
      }
    };

    preloadAudioFiles();
  }, []);

  /**
   * 播放通知声音
   * @param type 通知类型
   * @param customMessage 自定义语音消息（可选）
   */
  const playNotification = useCallback((
    type: NotificationType = 'message',
    customMessage?: string
  ) => {
    if (!isAudioReady || !settings.enabled) {
      return;
    }

    try {
      // 播放通知声音 - 消息类型强制音量0.2，其他类型使用设置音量
      const volume = type === 'message' ? 0.2 : settings.volume;
      playNotificationSound(type, volume);

      // 如果启用了语音提示，播放语音
      if (settings.voiceEnabled) {
        const voiceMessage = customMessage || getDefaultVoiceMessage(type);
        playVoiceNotification(voiceMessage);
      }
    } catch (error) {
      console.warn('播放通知失败:', error);
    }
  }, [isAudioReady, settings.enabled, settings.volume, settings.voiceEnabled]);

  /**
   * 播放新消息通知
   * @param messageCount 消息数量
   * @param isImportant 是否重要消息
   */
  const playNewMessageNotification = useCallback((messageCount: number = 1, isImportant: boolean = false) => {
    if (!isAudioReady || !settings.enabled) {
      return;
    }

    const type: NotificationType = isImportant ? 'alert' : 'message';
    const voiceMessage = isImportant 
      ? `您有${messageCount}条重要未读消息，请及时查阅`
      : `您有${messageCount}条未读消息，请及时查阅`;

    playNotification(type, voiceMessage);
  }, [isAudioReady, settings.enabled, playNotification]);

  /**
   * 播放任务提醒通知（优化版，解决破音问题）
   * @param taskName 任务名称
   * @param isUrgent 是否紧急
   */
  const playTaskNotification = useCallback((taskName: string, isUrgent: boolean = false) => {
    if (!isAudioReady || !settings.enabled) {
      return;
    }

    // 确保音频已经预加载完成
    if (!isPreloaded) {
      console.warn('音频尚未预加载完成，延迟播放任务通知');
      setTimeout(() => playTaskNotification(taskName, isUrgent), 150);
      return;
    }

    // 额外的预热延迟，确保音频系统完全准备就绪
    setTimeout(() => {
      const type: NotificationType = isUrgent ? 'alert' : 'message';
      const voiceMessage = isUrgent 
        ? `紧急任务提醒：${taskName}即将到期，请及时处理`
        : `任务提醒：${taskName}即将到期，请及时处理`;

      playNotification(type, voiceMessage);
    }, 50); // 50ms的额外预热时间
  }, [isAudioReady, settings.enabled, playNotification, isPreloaded]);

  /**
   * 播放系统通知
   * @param title 通知标题
   * @param isImportant 是否重要
   */
  const playSystemNotification = useCallback((title: string, isImportant: boolean = false) => {
    if (!isAudioReady || !settings.enabled) {
      return;
    }

    const type: NotificationType = isImportant ? 'alert' : 'message';
    const voiceMessage = isImportant 
      ? `重要系统通知：${title}`
      : `系统通知：${title}`;

    playNotification(type, voiceMessage);
  }, [isAudioReady, settings.enabled, playNotification]);

  return {
    playNotification,
    playNewMessageNotification,
    playTaskNotification,
    playSystemNotification,
    isAudioReady,
    audioEnabled: settings.enabled,
    voiceEnabled: settings.voiceEnabled,
    isPreloaded
  };
}

/**
 * 获取默认的语音消息
 */
function getDefaultVoiceMessage(type: NotificationType): string {
  switch (type) {
    case 'message':
      return '您有新的消息通知，请及时查阅';
    case 'alert':
      return '您有新的重要通知，请及时处理';
    case 'success':
      return '操作成功完成';
    case 'error':
      return '操作出现错误，请检查';
    default:
      return '您有新的通知，请及时查阅';
  }
}